package com.mdd.front.service.impl.yangyangLeadingEnterprise;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mdd.common.entity.yangyangLeadingEnterprise.TAppOrder;
import com.mdd.common.entity.yangyangLeadingEnterprise.TAppOrderItem;
import com.mdd.common.entity.yangyangLeadingEnterprise.TAppReport;
import com.mdd.common.entity.yangyangLeadingEnterprise.TAppUser;
import com.mdd.common.entity.yangyangLeadingEnterprise.common.JsonReturn;
import com.mdd.common.entity.yangyangLeadingEnterprise.dto.ReportDTO;
import com.mdd.common.entity.yangyangLeadingEnterprise.param.AppReportParam;
import com.mdd.common.entity.yangyangLeadingEnterprise.param.ReportAuthorizationLinkParam;
import com.mdd.common.mapper.yangyangLeadingEnterprise.TAppReportMapper;
import com.mdd.common.mapper.yangyangLeadingEnterprise.TAppUserMapper;
import com.mdd.common.util.ToolUtils;
import com.mdd.common.util.weifengqi.WFQUtil;
import com.mdd.common.util.weifengqi.authorize.AuthorizeReportUtil;
import com.mdd.common.util.weifengqi.authorize.AuthorizeUtil;
import com.mdd.front.service.yangyangLeadingEnterprise.ITAppOrderService;
import com.mdd.front.service.yangyangLeadingEnterprise.ITAppReportService;
import org.apache.commons.math3.util.Pair;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 财税报告实现类
 * @author LikeAdmin
 */
@Service
public class TAppReportServiceImpl implements ITAppReportService {
        
    @Resource
    TAppReportMapper appReportMapper;

    @Resource
    TAppUserMapper appUserMapper;

    @Resource
    ITAppOrderService appOrderService;

    @Override
    public List<TAppReport> selectList() {
        QueryWrapper<TAppReport> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("sort");
        return Optional.ofNullable(appReportMapper.selectList(wrapper)).orElse(new ArrayList<>());
    }

    public void initReport(){
        List<String> list = Arrays.asList("finance_service_analysis:融资服务报告"
                , "tax_risk_check:税务风险报告-通用版"
                , "tax_risk_check_simple:税务风险报告-简版"
                , "tax_risk_check_professional:税务风险报告-税优版"
                , "jindiao_company_analysis:企业尽调报告"
                , "fiscal_subsidies_analysis:财政补贴报告"
                , "jindiao_supplier_analysis:供应商尽调报告"
                , "business_strategy_analysis:经营参谋报告"
                , "invest_jindiao_analysis:投资尽调报告"
        );
        list.parallelStream().forEach(item->{
            String name=item.split(":")[1];
            String key=item.split(":")[0];
            TAppReport report = new TAppReport();
            report.setName(name);
            report.setIntroduce(name);
            report.setPreviewUrl("https://yylq-file.oss-cn-beijing.aliyuncs.com/uploads/16_%E8%9E%8D%E8%B5%84%E6%9C%8D%E5%8A%A1%E6%8A%A5%E5%91%8A-20250427112047.pdf");
            report.setCreateTime(new Date());
            report.setUpdateTime(new Date());
            report.setPrice(0.1);
            report.setReportKey(key);
            appReportMapper.insert(report);
        });

    }

    @Override
    public String reportAuthorizationLink(ReportAuthorizationLinkParam param) {
        String idListJsonArr = param.getIdListJsonArr();
        String companyName = param.getCompanyName();
        String taxId = param.getTaxId();
        if(idListJsonArr==null || idListJsonArr.isEmpty() || companyName==null || companyName.isEmpty() || taxId==null || taxId.isEmpty()){
            return JsonReturn.fail("必传参数不能为空！",40001).toJsonStr();
        }
        JSONArray jsonArray = JSONArray.parseArray(idListJsonArr);
        List<String> idList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            String id = jsonArray.getString(i);
            TAppReport report = appReportMapper.selectById(id);
            String reportKey = report.getReportKey();
            idList.add(reportKey);
        }
        //获取需要授权的报告
        String orderNo = ToolUtils.randomString(36);
        Pair<Boolean, String> pair = AuthorizeReportUtil.createParam(companyName,orderNo, idList);
        if(pair.getKey()){
            return JsonReturn.success().put("url",pair.getValue()).put("orderNo",orderNo).toJsonStr();
        }
        return JsonReturn.fail("获取授权链接失败", 40003).toJsonStr();
    }

    /**
     * 生成报告---创建报告订单
     * @param param
     * @return
     */
    @Override
    public String createReport(ReportAuthorizationLinkParam param) {
        Integer userId = param.getUserId();
        String orderNo = param.getOrderNo();
        String idListJsonArr = param.getIdListJsonArr();
        String companyName = param.getCompanyName();
        String taxId = param.getTaxId();
        Date now = new Date();
        if(userId==null|| orderNo==null || orderNo.isEmpty() || idListJsonArr==null || idListJsonArr.isEmpty() || companyName==null || companyName.isEmpty() || taxId==null || taxId.isEmpty()){
            return JsonReturn.fail("必传参数不能为空！",40001).toJsonStr();
        }
        JSONArray jsonArray = JSONArray.parseArray(idListJsonArr);
        List<TAppOrderItem> itemList = new ArrayList<>();
        Double totalPrice = 0.0;
        StringBuffer buffer = new StringBuffer("财税报告-");
        for (int i = 0; i < jsonArray.size(); i++) {
            String id = jsonArray.getString(i);
            TAppReport report = appReportMapper.selectById(id);
//            ReportDTO dto = WFQUtil.getReport("finance_service_analysis", orderNo, null,null);
            if(i==0){
                buffer.append(report.getName());
            }else{
                buffer.append("/").append(report.getName());
            }

            TAppOrderItem item = new TAppOrderItem();
            item.setReportId(report.getId());
            item.setPrice(report.getPrice());
            item.setNum(1);
            item.setCreateTime(now);
            item.setUpdateTime(now);
            totalPrice=totalPrice+Optional.ofNullable(report.getPrice()).orElse(0.0);
            itemList.add(item);
        }
        TAppOrder order = new TAppOrder();
        order.setOrderNo(orderNo);
        order.setOrderPrice(totalPrice);
        order.setOrderType(1);
        order.setCreateTime(now);
        order.setUpdateTime(now);
        order.setOrderStatus(1);
        order.setOrderPayStatus(1);
        order.setProductName(buffer.toString());
        order.setUserId(userId);
        order.setCompanyName(companyName);
        order.setCompanyTax(taxId);
        return JsonReturn.success().put("order",order).put("orderItemList",itemList).toJsonStr();
    }

    @Override
    public String preLoanReportAuthorizationLink(ReportAuthorizationLinkParam param) {
        AuthorizeUtil.createParam(param.getCompanyName());

        return "";
    }


}
